<template>
  <div class="container-fluid">
    <div class="row school-model school-tiao">
      <div class="col school-tiao-left">
        <span class="text-primary">{{ role.name }}</span>
        <span>{{ $route.name }}</span>
      </div>
      <div class="col text-right">
        <a-button type="primary">
          <router-link class="text-white" :to="{name: '机构角色'}">返回</router-link>
        </a-button>
      </div>
    </div>
    <div class="row school-model index-model">
      <div class="col school-col-table">
        <el-tree :data="authtype" show-checkbox node-key="ID" :props="defaultProps" ref="tree"></el-tree>
        <br />
        <div>
          <el-button @click="add">保存</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { asyncchangeschooolrole } from "../../../../plugins/api.js";
import { uniq } from "underscore";
export default {
  name: "watchrole",
  data() {
    return {
      defaultProps: {
        children: "children",
        label: "name"
      }
    };
  },
  props: ["ID"],
  computed: {
    ...mapGetters(["getschoolrole", "getschoolauthtype"]),
    authtype() {
      function a(x, id) {
        let arr = [];
        for (let v in x) {
          if (x[v].pid == id) {
            x[v].children = uniq(a(x, x[v].ID));
            arr.push(x[v]);
          }
        }
        return arr;
      }
      return a(this.getschoolauthtype);
    },
    getCheckedKeys() {
      return this.$refs.tree.getCheckedKeys();
    },
    role() {
      return this.getschoolrole.find(v => v.ID == this.ID);
    }
  },
  watch: {
    $route() {
      this.start();
    }
  },
  mounted() {
    this.start();
  },
  methods: {
    start() {
      const authtypes = this.role.authtypes;
      let checked = [];
      if (authtypes && authtypes.name) {
        checked = authtypes.name;
      }
      this.setCheckedKeys(checked);
    },
    async add() {
      const { ID, schoolid } = this.role;
      try {
        await asyncchangeschooolrole({
          ID,
          schoolid,
          authtypes: { name: this.getCheckedKeys }
        });
        await this.$store.dispatch("actionschoolrole");
        this.start();
        this.$message.success("修改成功");
      } catch (err) {
        this.$message.success(`修改失败:${err}`);
      }
    },
    setCheckedKeys(key) {
      this.$refs.tree.setCheckedKeys(key);
    }
  }
};
</script>

<style lang="scss" scoped>
.index-model {
  margin-top: 13px;
}
.dialog-footer {
  text-align: center;
}
.text-primary {
  display: inline-block;
  padding-right: 15px;
}
</style>